package model

import (
	"fmt"
	"gitee.com/liumou_site/logger"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/json"
	"strings"

	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	dnspod "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod/v20210323"
)

// GetParseList 获取域名解析列表
func (l *Login) GetParseList() {
	var res AutoGenerated
	if l.Debug {
		logger.Debug("正在获取域名解析列表")
	}
	// 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
	// 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
	// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
	credential := common.NewCredential(
		l.Domain.Login.Id,
		l.Domain.Login.Key,
	)
	// 实例化一个client选项，可选的，没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "dnspod.tencentcloudapi.com"
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, _ := dnspod.NewClient(credential, "", cpf)

	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := dnspod.NewDescribeRecordListRequest()

	request.Domain = common.StringPtr(l.Domain.Domain.Domain)
	request.Subdomain = common.StringPtr(l.Domain.Domain.Sub)
	//request.RecordType = common.StringPtr(l.IPS.IpType)

	// 返回的resp是一个DescribeRecordListResponse的实例，与请求对象对应
	response, err := client.DescribeRecordList(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		logger.Error("An API error has returned: ", err)
		return
	}
	if err != nil {
		panic(err)
	}
	//fmt.Println(response.ToJsonString())
	l.Err = json.Unmarshal([]byte(response.ToJsonString()), &res)
	if l.Err != nil {
		logger.Error("json格式化失败: ", err)
		return
	}
	// 输出json格式的字符串回包
	for _, v := range res.Response.RecordList {
		if l.Debug {
			fmt.Println(v)
		}
		info := DomainInfo{Sub: v.Name,
			Ip:       v.Value,
			RecordId: v.RecordID,
			Type:     v.Type}
		l.SubList = append(l.SubList, v.Name)
		l.DomainInfoList = append(l.DomainInfoList, info)
	}

}

// GetRecordId 获取RecordId
func (l *Login) GetRecordId() {
	if len(l.DomainInfoList) == 0 {
		l.GetParseList()
	}
	if len(l.DomainInfoList) == 0 {
		logger.Error("无法获取解析列表,请检查配置参数")
		return
	}
	l.Exists = false
	for _, v := range l.DomainInfoList {
		if strings.EqualFold(v.Sub, l.Domain.Domain.Sub) {
			if l.Debug {
				logger.Debug("记录已存在...")
			}
			l.Exists = true
			l.RecordId = v.RecordId
			if strings.EqualFold(v.Type, "AAAA") {
				l.RecordId6 = v.RecordId
			}
			if strings.EqualFold(v.Type, "A") {
				l.RecordId4 = v.RecordId
			}
			if l.Debug {
				logger.Debug("当前解析ID: ", l.RecordId)
			}
			return
		}
	}
}

// GetAnalyticalValue 获取记录值(某个解析记录的全部解析信息)
func (l *Login) GetAnalyticalValue() error {
	for _, v := range l.DomainInfoList {
		if v.RecordId == l.RecordId {
			l.Value = v.Ip
			return nil
		}
	}
	return fmt.Errorf("无法获取解析记录")
}
